<template>
    <div class="preview-form" v-if="visible">
        <div class="final-preview">
            <div class="final-preview-inner">
                <div class="preview-title">
                    {{ page.title }}
                </div>
                <div class="iframe-container">
                    <iframe :src="previewUrl" width="375" frameborder="0"
                    :height="page &&page.props&&page.props.height? page.props.height: '560'"></iframe>
                </div>
            </div>
        </div>
        <a-drawer title="设置面板" placement="right" width="400" :close="true" :open="visible" @close="onClose">
            <div class="publish-form-container">
                <a-row type="flex" align="middle" :style="{ marginBottom: '20px' }">
                <a-col :span="6">
                    扫码预览：
                </a-col>
                <a-col :span="10">
                    <canvas id="preview-barcode-container">

                    </canvas>
                </a-col>
                </a-row>
                <a-row type="flex" align="middle" :style="{ marginBottom: '20px' }">
                <a-col :span="6">
                    上传封面：
                </a-col>
                <a-col :span="18">
                    <BackgroundProcesser :value="form.uploaded.data.url" @change="updateAvatar"></BackgroundProcesser>
                </a-col>
                </a-row>
                <a-form
                :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }"
                :model="form" :rules="rules"
                ref="publishForm"
                >
                <a-form-item label="标题" required name="title">
                    <a-input v-model:value="form.title" @change="updatePage('title', form.title)"/>
                </a-form-item>
                <a-form-item label="副标题" required name="subTitle">
                    <a-input v-model:value="form.subTitle" @change="updatePage('desc', form.subTitle)"/>
                </a-form-item>
                <a-form-item :wrapper-col="{ span: 18, offset: 4 }">
                    <a-button type="primary" @click="checkAndpublish" :loading="isPublishing">
                    发布
                    </a-button>
                    <a-button style="margin-left: 10px;" @click="saveWork" :loading="isSaving">
                    保存
                    </a-button>
                    <a-button style="margin-left: 10px;" @click="cancelEdit">
                    取消
                    </a-button>
                </a-form-item>
                </a-form>
            </div>
        </a-drawer>
    </div>
</template>
<script setup lang="ts" name="PreviewForm">
import { computed, ref, reactive, watch, onMounted, type Ref} from 'vue'
import { editorInfos } from '@/stores/editor'
import StyledUploader from '@/components/StyledUploader.vue'
import pinia from '@/stores/index'
import QRCode from 'qrcode'
import BackgroundProcesser from '@/components/elements/BackgroundProcesser.vue'
interface RuleFormInstance {
  validate: () => Promise<any>;
}

const baseH5URL ='http://localhost:7006/api/utils'
const editorStore = editorInfos(pinia)

const emits = defineEmits(['onClose', 'trigger-publish', 'trigger-save'])
const page = computed(()=>editorStore.page)
const previewUrl = computed(()=>`${baseH5URL}/p/${page.value.id}-${page.value.uuid}`)
const props = defineProps({
    visible: {
        type: Boolean,
        defaults: false
    },
    isSaving: Boolean,
    isPublishing: Boolean
})



const { title, desc, setting } = page.value
//const previewURL = `${baseH5URL}/p/preview/${page.value.id}-${page.value.uuid}`
const form = reactive({
    title: title || '',
    subTitle: desc || '',
    uploaded: { data: { url: (setting && setting.shareImg) || 'http://vue-maker.oss-cn-hangzhou.aliyuncs.com/vue-marker/5f79389d4737571e2e1dc7cb.png' } }
})
// in case title changed from outside
watch(() => page.value.title, (newTitle) => {
    if (newTitle) {
    form.title = newTitle
    }
})
onMounted(async() => {
    const ele = document.getElementById('preview-barcode-container') as HTMLCanvasElement
    if (ele) {
        // clear the element
        ele.innerHTML = ''
        // eslint-disable-next-line no-new
        try {
            await QRCode.toCanvas(ele, previewUrl.value, { width: 100 })
        } catch (err) {
            console.error(err)
        }
    }
})
const publishForm = ref() as Ref<RuleFormInstance>
const rules = {
    title: [
    { required: true, message: '标题不能为空', trigger: 'blur' }
    ],
    subTitle: [
    { required: true, message: '副标题不能为空', trigger: 'blur' }
    ]
}
const updatePage = (key: string, value: string, settings = false) => {
    editorStore.updatePage({ key, value, level: settings ? 'setting' : false })
}
const updateAvatar = (url: string) => {
    form.uploaded = {
    data: { url }
    }
    updatePage('shareImg', url, true)
}
const validate = () => {
    return publishForm.value.validate()
}
const checkAndpublish = () => {
    validate().then(() => { 
        emits('trigger-publish')
    })
}
const saveWork = () => {
    validate().then(() => {
        emits('trigger-save')
     })
}
const cancelEdit = () => {
    emits('onClose')
}




const onClose = () => {
  emits('onClose')
};
</script>
<style lang="scss" scoped>
    .uploader-contain {
        .uploader-container {
            width: 130px !important
        }
    }
    .final-preview {
        position: absolute;
        width: calc(100% - 400px);
        height: 100%;
        background: transparent;
        top: 0;
        left: 0;
        z-index: 1003;
        display: flex;
        align-items: center;
        justify-content: center;
        .final-preview-inner {
            width: 430px;
            height: 870px;
            padding: 60px 28px;
            position: relative;
            background: url(./../../assets/phone-back.png);
            background-size: cover;
            .preview-title {
                height: 44px;
                line-height: 44px;
                text-align: center;
                font-weight: bold;
            }
            .iframe-container {
                width: 100%;
                height: 706px;
                overflow-y: auto;
                overflow-x: hidden;
            }
            .iframe-placeholder
            {
                background: url('~@/assets/loading.svg') 50% 50% no-repeat;
                background-size: 50px;
            }
        }
    }
</style>
